import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class ClThread implements Runnable {

	private Peer peer;
	private MyFile file;
	private Socket sock;
	private OutputStream outStream;
	private InputStream inStream;
	private PrintWriter out;
	private Scanner in;

	public ClThread(Peer peer, MyFile file) {
		this.peer = peer;
		this.file = file;

	}

	@Override
	public void run() {
		// TODO Auto-generated method stub

		try {
			sock = new Socket(peer.getIP(), peer.getListenPort());
			//sock.setSoTimeout(5000);
			inStream = sock.getInputStream();
			outStream = sock.getOutputStream();
			out = new PrintWriter(outStream, true);
			in = new Scanner(inStream);

			download();
			// out.println("exit");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				sock.close();
				// System.out.println("client down");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
	
	public String extractName(String str){
		String buf[] = str.split("\\\\");
		buf = buf[buf.length-1].split("/");
		return buf[buf.length-1];
	}

	public void download() {
		int packetCount = 0;
		String tokens[] = new String[2];
		tokens[0] = new String();
		tokens[1] = new String();
		byte part[] = new byte[1024];
		int bytesRead = 0, bytes = 0, readPackets = 0;
		float progress = 0;
		File fileToDown = new File("downloads/" + extractName(file.getName()));
		fileToDown.mkdirs();
		fileToDown.delete();
		try {
			FileOutputStream fileIn = new FileOutputStream(fileToDown);

			String cmd = new String();
			out.println("download;" + file.getName() + ";" + file.getSize());
			while (in.hasNextLine()) {
				cmd = in.nextLine();
				tokens = cmd.split(";");
				if (tokens[0].compareTo("start") == 0)
					break;
				if (tokens[0].compareTo("packets") == 0)
					packetCount = Integer.parseInt(tokens[1]);
			}
			// System.out.println("rozpoczynam pobieranie! - pakiety " +
			// packetCount);
			Client.getMainFr().getDownloadPanel().getModel()
					.addFile(file.getName(), file.getSize(), 0);

			while (bytesRead < file.getSize()) {
			/*try {
				Thread.sleep(100);
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}*/
				try {
					bytes = 0;
					bytes = inStream.read(part);
					//System.out.println("po read bytes bytes    " + bytes);
					if (((readPackets == packetCount - 1) && (bytes != -1) && (bytes != 0))
							|| (bytes == 1024)) {
						out.println("ack" + readPackets);
						System.out.println("ack" + readPackets+"byt: "+bytes);
						readPackets++;
						bytesRead += bytes;
						fileIn.write(part, 0, bytes);
						progress = ((float) (bytesRead) / file.getSize()) * 100;
						Client.getMainFr()
								.getDownloadPanel()
								.getModel()
								.updateFile(file.getName(), file.getSize(),
										(int) progress);
						Client.getMainFr().getDownloadPanel()
								.getDownloadTable().repaint();
					} else {
						out.println("lost" + readPackets);
						//System.out.println("lost" + readPackets);
					}

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			System.out.println("po while");
			Client.getMainFr().getDownloadPanel().getModel()
					.updateFile(file.getName(), file.getSize(), 100);
			Client.getMainFr().getDownloadPanel().getDownloadTable().repaint();
			out.println("exit");
			fileIn.close();
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
